package unipi.servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;


import unipi.helpers.HTMLPages;
import unipi.helpers.LoginCookie;

public class Business extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	public Business()
	{
		super();
	}
	
	public void init() throws ServletException
	{
		
	
	}
	
	private String[] readXML(String filename)
	{
		String[] data = {"", "", ""};
		
		try
		{
			File xmlFile = new File(filename);
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(xmlFile);
			doc.getDocumentElement().normalize();
			
			NodeList nList = doc.getChildNodes();
			
			for (int temp = 0; temp < nList.getLength(); temp++)
			{				 
				   Node nNode = nList.item(temp);
				   if (nNode.getNodeType() == Node.ELEMENT_NODE)
				   {		 
				      Element eElement = (Element) nNode;
				      
				      data[0] = eElement.getElementsByTagName("logo").item(0).getChildNodes().item(0).getNodeValue();
				      data[1] = eElement.getElementsByTagName("name").item(0).getChildNodes().item(0).getNodeValue();
				      data[2] = eElement.getElementsByTagName("description").item(0).getChildNodes().item(0).getNodeValue();				      
				   	}
			}
			
				
		}
		catch(Exception e)
		{
			System.out.println("Exception reading xml file " + filename + " with message " + e.toString());
		}
		
		return data;		
	}
	
	private String getPage(String uid, String[] data)
	{
		String content = "<h1>Επιχείρηση</h1>" +
						"<img class=\"companyLogo\" src=\"custom/" + data[0] + "\" alt=\"\"/> " +
						"<div class=\"companyDescription\"><h3 class=\"companyName\">" + data[1] + "</h3>" +
						data[2] + "</div><div class=\"clear\"></div>";
		
		return HTMLPages.getGeneralPage(content, uid);		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		if(!LoginCookie.authCookie(request))
			response.sendRedirect("Login");
		else
		{
			String uid = LoginCookie.Get(request)[0];
			
			response.setContentType("text/html; charset=UTF-8");	
			PrintWriter out = response.getWriter();
			
			String[] data = readXML(request.getServletContext().getRealPath("custom/businessdata.xml"));
			
			out.println(getPage(uid, data));
			
			out.close();	
		}
	}

}
